var fs = require('fs')
const { baseDataPath,pathType } = require("../config");

function getDestination (req, file, cb) {
  cb(null, baseDataPath+req.body.name)
}

function getFilename (req, file, cb) {
  cb(null, file.originalname)
}

function MyCustomStorage (opts) {
  this.getDestination = (opts.destination || getDestination)
  this.getFilename = (opts.filename || getFilename)
}
MyCustomStorage.prototype._handleFile = function _handleFile (req, file, cb) {
  
  this.getDestination(req, file, (err, path) =>{
    if (err) return cb(err)
    this.getFilename(req, file, function (err, filename) {
      file.originalname = filename
    })
    var outStream = fs.createWriteStream(path.path+pathType+file.originalname)
    file.stream.pipe(outStream)
    outStream.on('error', (cb)=>{
      console.log('出错了',cb);
    })
    outStream.on('finish', function () {
      cb(null, {
        path: path.path.replace(path.base,'')+pathType+file.originalname,
        size: outStream.bytesWritten
      })
    })
  })
 
}

MyCustomStorage.prototype._removeFile = function _removeFile (req, file, cb) {
  fs.unlink(file.path, cb)
}

module.exports = function (opts) {
  return new MyCustomStorage(opts)
}